//
//  HRHomePageStatusViewModel.swift
//  weiBo
//
//  Created by helong on 16/7/14.
//  Copyright © 2016年 helong. All rights reserved.
//

import UIKit

class HRHomePageStatusViewModel: NSObject {

    //  持有HRHomePageModel
    var homePageModel: HRHomePageModel?
    
    // 拼接转发微博的文本
    var retweetContent: String?
    //  转发按钮的文字
    var retweetStr: String?
    //  评论按钮的文字
    var commentStr: String?
    //  赞按钮的文字
    var likeStr: String?
    //  用户等级的图片
    var mbrankeImage: UIImage?
    //  微博来源
    var weiBoResouce: String?
    //  微博认证等级
    var verifiedImage: UIImage?
    //  发微博的时间
    var creat_time: String?{
//        guard let createAtStr = self.homePageModel?.created_at else {
//            return nil
//        }
//    
//        return NSDate.creatTime(createAtStr).timeString
//        
        //  判断发布微博时间是否为nil
        guard let createAtStr = self.homePageModel?.created_at else {
            
            return nil
        }
        print(createAtStr)
        return NSDate.sinaDate(createAtStr).sinaDateString
    }

    //  原创微博的内容
    var originWeiboAttributeString: NSAttributedString?
    
     // MARK: - 初始化持有的微博模型
    init(homePageModel: HRHomePageModel) {
        super.init()
        //  用传进来的homePageModel初始化自己的homePageModel
        self.homePageModel = homePageModel
        //  拼接转发微博的类容
        handleRetweetContent(homePageModel)
        //  转发按钮的文字
        retweetStr = handleToolBarTitleString(homePageModel.reposts_count, title: "转发")
        //  评论按钮的文字
        commentStr = handleToolBarTitleString(homePageModel.comments_count, title: "评论")
        //  赞按钮的文字
        likeStr = handleToolBarTitleString(homePageModel.attitudes_count, title: "赞")
        //  显示会员等级
        handleMBrankImage(homePageModel.user?.mbrank ?? 0)
        //  微博来源, 空运算符转化
        handleRosource(homePageModel.source ?? "")
        //  微博认证等级
        handleVerifiedType(homePageModel.user?.verified_type ?? 0)
        //  处理微博内容中的表情图片
       originWeiboAttributeString = handleWeiboAttributedString(homePageModel.text!)
    }
    
     // MARK: - 微博认证等级
    private func handleVerifiedType(mbrank: Int){
        // -1 没有认证   0 是认证用户   2,3,5 企业认证   220 微博达人
        switch mbrank{
        case 0://   认证用户
            verifiedImage = UIImage(named: "avatar_vip")
        case 2, 3, 5 ://    企业认证
            verifiedImage = UIImage(named: "avatar_enterprise_vip")
        case 220 ://    微博达人
            verifiedImage = UIImage(named: "avatar_grassroot")
        default://  没有认证
            verifiedImage = nil
        }
    }
     // MARK: - 微博的来源
    private func handleRosource(resource: String){
        //  截取字符串  返回字符传递额格式:("<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">微博 weibo.com</a>")
        //  "> 字符的range
        guard let range1 = resource.rangeOfString("\">") else{
            return
        }
        
//        let start = range1.endIndex
//        let end = range2.startIndex
        //  截取一个范围内的字符串
        let str1 = resource.substringFromIndex(range1.endIndex)
        guard let range2 = str1.rangeOfString("</") else{
            return
        }
        weiBoResouce = str1.substringToIndex(range2.startIndex)
  
    }
     // MARK: - 是否显示会员等级
    private func handleMBrankImage(count: Int){
        if count >= 0 && count <= 6 {
           mbrankeImage = UIImage(named: "common_icon_membership_level\(count)")
        }else{
            mbrankeImage = UIImage(named: "common_icon_membership_expired")
        }
    }

     // MARK: - 判断按钮文字的显示
    private func handleToolBarTitleString(count: Int, title: String) -> String{
        
        if count < 0 {//  小于0,显示文字
            return title
        }else if count < 10000 {// 0~1000之间,显示数字
            return "\(count)"
        }else{//  >10000,显示数字加文字: 1.1万
            let count1 = count / 1000
            let count2 = CGFloat(count1 / 10)
            var str = "\(count2)万"
            //  如果数字以   .0   结尾,那么其去掉
            if str.containsString(".0") {
                //  替换字符串的方法
               str =  str.stringByReplacingOccurrencesOfString(".0", withString: "")
            }
            return str
        }
    }
     // MARK: - 根据传递进来的 HRHomePageModel 模型类容,拼接转发微博的类容
    private func handleRetweetContent(homePageModel: HRHomePageModel){
        if homePageModel.retweeted_status != nil {

            guard let name = homePageModel.user?.screen_name, let text = homePageModel.retweeted_status?.text else{
                return
            }
            //  拼接转发微博的类容
            retweetContent = "@\(name): \(text)"
        }
    }
    
     // MARK: - 处理微博中的表情
    private func handleWeiboAttributedString(text: String) -> NSAttributedString{
        
        let attributeString = NSMutableAttributedString(string: text)
        var resultSet = [HRMatchResult]()
        //  使用正则表达式找出表情描述的字符串及其range
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (matchCount, matchString, matchRange, _) -> Void in

            //  把查找到的内容保存在模型中
            guard let chs = matchString.memory as? String else {
                return
            }
            let result = HRMatchResult(matchString: chs, matchRange: matchRange.memory)
            
            resultSet.append(result)
        }
        for value in resultSet.reverse() {
            //  根据chs获取对应的模型
            if let emotion = HREmotionManager.manager.getEmotionFromChs(value.matchString!) {
            //  拿到模型转化成富文本(可以抽取到textView中)
                let attrubuteString =  HREmotionManager.manager.generateAttributeStringWithEmotion(HomePageFontSize, emotion: emotion)
//                print(emotion.chs)
//                let attachment = HRTextAttachment()
//                attachment.image = UIImage(named: emotion.absolutePathForPNG!)
//                let attribueStr = NSAttributedString(attachment: attachment)
                
                //  替换文本中富文本
                attributeString.replaceCharactersInRange(value.matchRange!, withAttributedString: attrubuteString)
                print(value.matchRange)
            }
        }
        return attributeString
    }
}
